use rusqlite::ToSql;
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef};
use serde::{Deserialize, Serialize};

#[derive(Debug, Default, Clone, Serialize, Deserialize, Eq, PartialEq)]
pub(crate) enum ComponentV2raySubscriptionLastUpdateState {
    #[default]
    NotRun,
    Success,
    Failed,
}

impl ToSql for ComponentV2raySubscriptionLastUpdateState {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
        match *self {
            ComponentV2raySubscriptionLastUpdateState::NotRun => Ok(ToSqlOutput::Owned(rusqlite::types::Value::Text("NotRun".to_string()))),
            ComponentV2raySubscriptionLastUpdateState::Success => Ok(ToSqlOutput::Owned(rusqlite::types::Value::Text("Success".to_string()))),
            ComponentV2raySubscriptionLastUpdateState::Failed => Ok(ToSqlOutput::Owned(rusqlite::types::Value::Text("Failed".to_string()))),
        }
    }
}


impl FromSql for ComponentV2raySubscriptionLastUpdateState {
    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
        match value.as_str() {
            Ok("NotRun") => Ok(ComponentV2raySubscriptionLastUpdateState::NotRun),
            Ok("Success") => Ok(ComponentV2raySubscriptionLastUpdateState::Success),
            Ok("Failed") => Ok(ComponentV2raySubscriptionLastUpdateState::Failed),
            _ => Err(FromSqlError::InvalidType),
        }
    }
}

#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub(crate) struct ComponentV2raySubscription {
    pub(crate) uuid: String,
    pub(crate) name: String,
    pub(crate) url: String,
    pub(crate) enabled: bool,
    pub(crate) auto_update: bool,
    pub(crate) last_update_time: i64,
    pub(crate) last_update_state: ComponentV2raySubscriptionLastUpdateState,
}